//
//  SearchCompanyViewController.m
//  AddressBook
//
//  Created by mac on 2017/8/26.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "SearchCompanyViewController.h"
#import "CompanyViewController.h"

@interface SearchCompanyViewController () <UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>{
    id _oberver;
}

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UITextField *searchField;
@property (nonatomic, strong) NSMutableArray *dataSource;
//@property (nonatomic ,strong) NSDictionary *userData;
@property (nonatomic, strong) NSString *com_name;
@property (nonatomic, strong) UserDataModel *model;

@end

@implementation SearchCompanyViewController

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:_oberver];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"查询";
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
//    self.userData = [[NSUserDefaults standardUserDefaults] objectForKey:KUSERINFORMATION];
    self.model = [UserDataModel getLocalModel];
    [self initializeAppearence];
    _oberver = [[NSNotificationCenter defaultCenter] addObserverForName:UITextFieldTextDidEndEditingNotification object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
        [self initalizeDataSource:self.searchField.text];
    }];
}


-(void)initializeAppearence{
    
    [self.view addSubview:self.searchField];
    [self.view addSubview:self.tableView];
    self.dataSource = [NSMutableArray array];
}

-(void)initalizeDataSource:(NSString *)text{
    [self showHudInView:self.view hint:@"搜索中"];
    NSString *url = [NSString stringWithFormat:@"%@%@",MAIN_URL,COMPANY_URL];
    NSDictionary *dic = @{@"com_name":text};
    [NetworkRequestManager postWithUrl:url parameter:dic success:^(id requestData) {
        NSLog(@"%@",requestData);
        if ([dic[@"code"] isEqualToString:@"20000"]) {
            [self hideHud];
            [self showHint:@"查询参数不存在"];
        }else if ([requestData[@"code"] isEqualToString:@"10000"]){
            [self hideHud];
            self.dataSource = [requestData[@"data"] mutableCopy];
            CompanyViewController *com = [[CompanyViewController alloc]init];
            //com.companyArray = self.dataSource;
            [self.tableView reloadData];
        }
        
    } failure:^(NSError *error) {
        [self hideHud];
        NSLog(@"%@",error);
    }];
    
}

-(void)addCompanyAlertShow:(NSString *)message{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"申请加入" message:[NSString stringWithFormat:@"是否申请加入%@",message] preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self showHudInView:self.view hint:@"申请中，请稍等"];
        NSString *url = [NSString stringWithFormat:@"%@%@",MAIN_URL,APPLYFOR_URL];
        //NSDictionary *dic = @{@"user_name":self.model.userinfo[@"member_name"],@"member_phone":self.model.userinfo[@"phone_name"][0][@"phone"] ,@"com_name":self.com_name,@"id_card":self.model.userinfo[@"id_card"]};
        NSDictionary *dic = @{@"user_name":@"修改了model结构" ,@"member_phone":@"修改了model结构" ,@"com_name":self.com_name,@"id_card":@"修改了model结构"};
        [NetworkRequestManager postWithUrl:url parameter:dic success:^(id requestData) {
            
            if ([requestData[@"code"] isEqualToString:@"20000"]) {
                [self hideHud];
                [self showHint:@"申请加入该公司失败"];
            }else{
                [self hideHud];
            }
        } failure:^(NSError *error) {
            [self hideHud];
            [self showHint:@"申请失败"];
        }];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark -  UITextFieldDelegate;
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    [self.searchField resignFirstResponder];
    return YES;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static  NSString  *string=@"SerUITableViewCell";
    UITableViewCell  *cell=[tableView dequeueReusableCellWithIdentifier:string];
    if (!cell) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:string];
    }
    
    cell.textLabel.text = self.dataSource[indexPath.row][@"com_name"];
    self.com_name =  self.dataSource[indexPath.row][@"com_name"];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"%@",self.dataSource[indexPath.row]);
//    NSString *str = [[NSString alloc]initWithData:self.dataSource[indexPath.row][@"com_name"] encoding:NSUTF8StringEncoding];
    [self addCompanyAlertShow:self.com_name];
    
}

#pragma mark - setter与getter
- (UITextField *)searchField
{
    if (!_searchField) {
        _searchField=[[UITextField alloc]initWithFrame:CGRectMake(0, 0, ScreenW , 40)];
        _searchField.delegate=self;
        _searchField.backgroundColor=[UIColor whiteColor];
//        _searchField.layer.cornerRadius=10;
        _searchField.clearButtonMode = UITextFieldViewModeAlways;
        _searchField.placeholder=@"搜索公司";
        [_searchField canBecomeFirstResponder];
        _searchField.font=[UIFont systemFontOfSize:17];
        _searchField.autocapitalizationType=UITextAutocapitalizationTypeNone;;
        _searchField.clearButtonMode=UITextFieldViewModeWhileEditing;
        _searchField.returnKeyType=UIReturnKeySearch;
        
        UIView * userLeft = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
        UIImageView * left = [[UIImageView alloc]initWithFrame:CGRectMake(5, 7.5, 25,25)];
        left.image = [UIImage imageNamed:@"搜索图标"];
        [userLeft addSubview:left];
        _searchField.leftViewMode = UITextFieldViewModeAlways;
        _searchField.leftView = userLeft;
        
    }
    return _searchField;
}

- (UITableView *)tableView{
    
    if (!_tableView) {
        _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.searchField.frame)+5, ScreenW, ScreenH - CGRectGetHeight(self.searchField.frame)) style:UITableViewStylePlain];
        _tableView.dataSource=self;
        _tableView.delegate=self;
        _tableView.showsHorizontalScrollIndicator = YES;
    }
    return _tableView;
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
    
}


@end
